package com.campfire.intelligentsecurity.business.service;

import cn.hutool.core.util.StrUtil;
import com.campfire.intelligentsecurity.business.bean.TSysUser;
import com.campfire.intelligentsecurity.sys.kit.AESUtil;
import com.campfire.intelligentsecurity.sys.service.BaseService;
import com.github.drinkjava2.jsqlbox.DbContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import static com.github.drinkjava2.jsqlbox.DB.*;

@Service
public class UserService extends BaseService {

    @Autowired
    @Qualifier("main")
    DbContext dbContext;

    public Object userList() {
        return builder("SELECT a.id, a.username, a.usercode, a.enable, a.createTime, b.lastLogin, a.delable " +
                "FROM t_sys_user a " +
                "left join (" +
                "select max(createTime) lastLogin, userid from t_sys_login_log group by userid" +
                ") b on a.id = b.userid " +
                "where 1=1");
    }

    public Object loadInfo(String id) {
        if (StrUtil.isNotEmpty(id)) {
            return dbContext.qryMap("select id, username, usercode, enable from t_sys_user where id=?", par(id));
        } else {
            return null;
        }
    }

    public Object saveOrUpdate(TSysUser sysUser) {
        if("".equals(sysUser.getPassword())){
            sysUser.setPassword(null);
        }else{
            sysUser.setPassword(AESUtil.encode(sysUser.getPassword()));
        }
        if (sysUser.getId() != null) {
            dbContext.exe("update t_sys_user set ",
                    notBlank("password=?, ", sysUser.getPassword()),
                    " username=?, usercode=?, enable = ? where id = ?", par(sysUser.getUsername(), sysUser.getUsercode(), sysUser.getEnable(), sysUser.getId()));
        } else {
            sysUser.insert();
        }
        return true;
    }

    public Object remove(String ids) {
        return dbContext.exe("delete from t_sys_user where id in('" + ids.replaceAll(",", "','") + "')");
    }

    public Object chengeState(String id, String state) {
        return dbContext.exe("update t_sys_user set enable = ? where id = ?", par(state, id));
    }

    public int isExist(String usercode, String userid) {
        return dbContext.qryIntValue("select count(*) as num from t_sys_user where 1=1",
                noBlank(" and usercode =?", usercode),
                noBlank(" and id !=?", userid));
    }
}
